#include "precompiled.h"
#include "myCBIR_VideoOutputWidget.h"

namespace myCBIR
{
    VideoOutputWidget::VideoOutputWidget(FrameCapture* existingCaptureDevice, FaceDetector *faceDetector)
    {
        pCaptureDevice = existingCaptureDevice;
        if(existingCaptureDevice != 0)
            existingCaptureDevice->addFrameReceiver(this);
        pFaceDetector = faceDetector;
    }

    VideoOutputWidget::VideoOutputWidget(const std::string &winName, FrameCapture* existingCaptureDevice, FaceDetector *faceDetector)
    {
        pCaptureDevice = existingCaptureDevice;
        if(existingCaptureDevice != 0)
        {
            if (existingCaptureDevice->addFrameReceiver(this))
                printf("Receiver added! \n");
        }
        
        sWinName = winName;
        pFaceDetector = faceDetector;
    }

    VideoOutputWidget::~VideoOutputWidget()
    {

    }

    void VideoOutputWidget::update()
    {
        loadNextFrameIntoCurrent();
        pFaceDetector->processFrame();
        for (myCBIR::Detector::RectVectorItr i = faces.begin(); i != faces.end(); ++i)
        {
            cv::rectangle(
                currentFrame,*i,
                cv::Scalar(0, 0, 255)
                );
        }
        cv::imshow(sWinName.c_str(), currentFrame);
        if (cv::waitKey(5) == 'u')
            pCaptureDevice->stopCapturing();
    }

    void VideoOutputWidget::receiveFrame(const cv::Mat &frame)
    {
        //printf("frame received! \n");
       // frameLoadLock.lock();

        //nextFrame = frame.clone();
        nextFrame = frame;

       // frameLoadLock.unlock();

        //update causes a paintEvent, which calls loadNextFrameIntoCurrent
        //this could cause deadlock
        update();
    }
    void VideoOutputWidget::stateChanged(Detector *detector)
    {
        faces = detector->getAreas();
    }

    void VideoOutputWidget::loadNextFrameIntoCurrent()
    {
        //boost::lock_guard<boost::mutex>(this->frameLoadLock);

        currentFrame = nextFrame;
    }
}